package com.zbar.lib;

import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Point;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.util.DisplayMetrics;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.bean.ProjectItemBean;
import com.hongxun.design.interfaces.HeadSecond;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.ui.headandbottonpanel.HeadSecondControlPanel;
import com.hongxun.design.utils.DataUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.zbar.lib.camera.CameraManager;
import com.zbar.lib.decode.CaptureActivityHandler;
import com.zbar.lib.decode.InactivityTimer;

import java.io.IOException;

/**
 * 二维码扫描
 */
public class CaptureActivity extends Activity implements HeadSecond,Callback {

	private CaptureActivityHandler handler;
	private boolean hasSurface;
	private InactivityTimer inactivityTimer;
	private MediaPlayer mediaPlayer;
	private boolean playBeep;
	private static final float BEEP_VOLUME = 0.50f;
	private boolean vibrate;
	private int x = 0;
	private int y = 0;
	private int cropWidth = 0;
	private int cropHeight = 0;
	private RelativeLayout mContainer = null;
	private RelativeLayout mCropLayout = null;
	private boolean isNeedCapture = false;

	public boolean isNeedCapture() {
		return isNeedCapture;
	}

	public void setNeedCapture(boolean isNeedCapture) {
		this.isNeedCapture = isNeedCapture;
	}

	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}

	public int getCropWidth() {
		return cropWidth;
	}

	public void setCropWidth(int cropWidth) {
		this.cropWidth = cropWidth;
	}

	public int getCropHeight() {
		return cropHeight;
	}

	public void setCropHeight(int cropHeight) {
		this.cropHeight = cropHeight;
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_scanner);
		findBar();
		// 初始化CameraManager
		CameraManager.init(getApplication());
		hasSurface = false;
		inactivityTimer = new InactivityTimer(this);

		mContainer = (RelativeLayout) findViewById(R.id.capture_containter);
		mCropLayout = (RelativeLayout) findViewById(R.id.capture_crop_layout);
//		findViewById(R.id.loca_show_btncancle).setOnClickListener(
//				new OnClickListener() {
//
//					@Override
//					public void onClick(View arg0) {
//						finish();
//					}
//				});
//		// 获得屏幕的宽高
		DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
		int screenWith = displayMetrics.widthPixels;
		LayoutParams params = (LayoutParams) mCropLayout.getLayoutParams();
		params.width = screenWith * 2 / 3;
		params.height = screenWith * 2 / 3;
		mCropLayout.setLayoutParams(params);
		ImageView mQrLineView = (ImageView) findViewById(R.id.capture_scan_line);
		TranslateAnimation mAnimation = new TranslateAnimation(
				TranslateAnimation.ABSOLUTE, 0f, TranslateAnimation.ABSOLUTE,
				0f, TranslateAnimation.RELATIVE_TO_PARENT, 0f,
				TranslateAnimation.RELATIVE_TO_PARENT, 0.9f);
		mAnimation.setDuration(1500);
		mAnimation.setRepeatCount(-1);
		mAnimation.setRepeatMode(Animation.REVERSE);
		mAnimation.setInterpolator(new LinearInterpolator());
		mQrLineView.setAnimation(mAnimation);
	}
	String type = "", title = "";
	@Override
	public void findBar() {
		Bundle bundle = getIntent().getExtras();
		title = bundle.getString(MString.TITLE);
		type = bundle.getString(MString.TYPE);
		HeadSecondControlPanel headsecond_layout = (HeadSecondControlPanel) findViewById(R.id.viewfinder_layout);
		headsecond_layout.initHeadPanel(DataUtil.getsecondbean("", View.GONE, R.color.bar_right, new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		}, title, R.color.title, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
	}
	boolean flag = true;

	protected void light() {
		if (flag == true) {
			flag = false;
			// 打开
			CameraManager.get().openLight();
		} else {
			flag = true;
			// 关闭
			CameraManager.get().offLight();
		}

	}

	@SuppressWarnings("deprecation")
	@Override
	protected void onResume() {
		super.onResume();
		SurfaceView surfaceView = (SurfaceView) findViewById(R.id.capture_preview);
		SurfaceHolder surfaceHolder = surfaceView.getHolder();
		if (hasSurface) {
			initCamera(surfaceHolder);
		} else {
			surfaceHolder.addCallback(this);
			surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}
		playBeep = true;
		AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
		if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
			playBeep = false;
		}
		initBeepSound();
		vibrate = true;
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (handler != null) {
			handler.quitSynchronously();
			handler = null;
		}
		CameraManager.get().closeDriver();
	}

	@Override
	protected void onDestroy() {
		inactivityTimer.shutdown();
		super.onDestroy();
	}

	public void handleDecode(String rawResult) {
		inactivityTimer.onActivity();
		playBeepSoundAndVibrate();
		if (rawResult!=null&&rawResult.length()>0){
			switch (type) {
				case MString.ScanToFind:
					Intent intent = getIntent();
					intent.putExtra(MString.codedContent, rawResult);
					setResult(RESULT_OK, intent);
					break;
				case MString.ScanToScan:
					projectReturn(rawResult);
					break;
				case MString.Scanproject:
					projectReturn(rawResult);
					break;

			}
			finish();
		}





//		Intent mIntent = new Intent();
//		mIntent.putExtra("QR_CODE", result);
//		// 设置结果，并进行传送
//		this.setResult(RESULT_OK, mIntent);
//
//		// Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT)
//		// .show();
//		finish();

	}
	private void projectReturn(String rawResult) {
		try {

			String  s=rawResult;
//            CodeErWeiBean bean = FastJsonUtil.JsonToGetCodeErWei(s);
			ProjectItemBean b = FastJsonUtil.JsonToGetProject(s);
			if (MyApp.File.saveProjectList(b)){
				ToastShow.showShort(this, "项目:"+b.project_name+",接收成功！");
			}else{
				ToastShow.showShort(this,"权限不足,接收失败！");
				this.finish();
			}
		}catch (Exception e){
			ToastShow.showShort(this,"读取错误,接收失败！");
		}
//        ProjectItemBean b = FastJsonUtil.JsonToGetProject(rawResult.getText());
//        String ReceiveJson = MyApp.File.ReadFileData(MString.ProjectStageReviceListFile);
//        List<ProjectItemBean> data;
//        if (ReceiveJson != null && ReceiveJson.length() > 0) {
//            data = FastJsonUtil.JsonToGetProjectListBean(ReceiveJson);
//            for (ProjectItemBean p : data) {
//                if (p.getStage_id().equals(b.getStage_id())) {
//                    data.remove(p);
//                    break;
//                }
//            }
//            data.add(0,b);
//
//        } else {
//            data = new ArrayList<>();
//            data.add(b);
//        }
//        MyApp.File.SaveFileData(MString.ProjectStageReviceListFile,"{" +"\"projectList\":"+ JSON.toJSONString(data)+"}", "no");//存储
//        FragmentUtil.getIntence(this).projectFragment.onRefresh();
	}
	private void initCamera(SurfaceHolder surfaceHolder) {
		try {
			CameraManager.get().openDriver(surfaceHolder);

			Point point = CameraManager.get().getCameraResolution();
			int width = point.y;
			int height = point.x;

			int x = mCropLayout.getLeft() * width / mContainer.getWidth();
			int y = mCropLayout.getTop() * height / mContainer.getHeight();

			int cropWidth = mCropLayout.getWidth() * width
					/ mContainer.getWidth();
			int cropHeight = mCropLayout.getHeight() * height
					/ mContainer.getHeight();

			setX(x);
			setY(y);
			setCropWidth(cropWidth);
			setCropHeight(cropHeight);
			setNeedCapture(true);

		} catch (IOException ioe) {
			return;
		} catch (RuntimeException e) {
			return;
		}
		if (handler == null) {
			handler = new CaptureActivityHandler(CaptureActivity.this);
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (!hasSurface) {
			hasSurface = true;
			initCamera(holder);
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		hasSurface = false;

	}

	public Handler getHandler() {
		return handler;
	}

	private void initBeepSound() {
		if (playBeep && mediaPlayer == null) {
			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setOnCompletionListener(beepListener);

			AssetFileDescriptor file = getResources().openRawResourceFd(
					R.raw.beep);
			try {
				mediaPlayer.setDataSource(file.getFileDescriptor(),
						file.getStartOffset(), file.getLength());
				file.close();
				mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
				mediaPlayer.prepare();
			} catch (IOException e) {
				mediaPlayer = null;
			}
		}
	}

	private static final long VIBRATE_DURATION = 200L;

	private void playBeepSoundAndVibrate() {
		if (playBeep && mediaPlayer != null) {
			mediaPlayer.start();
		}
		if (vibrate) {
			Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
			vibrator.vibrate(VIBRATE_DURATION);
		}
	}

	private final OnCompletionListener beepListener = new OnCompletionListener() {
		public void onCompletion(MediaPlayer mediaPlayer) {
			mediaPlayer.seekTo(0);
		}
	};
}